<?php


namespace app\common\command;

use app\common\cachemodel\Recode;
use app\common\lib\Util;
use app\common\model\User;
use app\everyday\controller\IndexJob;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;

class UserFortuneDay extends Command
{
    /**
     * 命令配置
     */
    protected function configure()
    {
        $this->setName('user:fortune_day')->setDescription('生成用户日运数据入库');
    }

    protected function execute(Input $input, Output $output)
    {
        $startDate = '2020-01-01';
        $endDate = '2020-12-31';
        // 检查数据库表是否建立
        $this->tablesCheck();
        // Util::queuePush('fortune_day', ['start_date' => '2020-01-01', 'end_date' => '2020-01-31', 'uids' => 2]);
        try
        {
            $page = 1;
            $totalNum = 0;
            $taskNum = 0;
            $id = 0;
            do
            {
                print_r('step:1,准备查数据');
                $data = (new Recode())
                    ->where('id', '>', $id)->where(['isself' => 1])->whereNotIn('uid', function ($query)
                    {
                        $query->table('wechat_backup_07_18_14_43_00.zl_user_xz')->field('uid');
                    })
                    ->page(1, 100)
                    ->order('id asc')
                    ->column('id', 'uid');
                print_r('step:2,数据查询成功，准备发送到队列');
                if ($data)
                {
                    Util::queuePush('fortune_day', [
                        'start_date' => $startDate,
                        'end_date' => $endDate,
                        'uids' => array_keys($data)
                    ]);
                    $id = array_pop($data);
                    $taskNum++;
                    print_r('日运计算添加队列完成，page=' . $page . PHP_EOL);
                }
                $page++;
                $num = count($data);
                $totalNum += $num;
            } while ($num > 0);
        }
        catch (\Exception $e)
        {
            print_r('日运计算错误：' . $e->getMessage() . PHP_EOL);
        }
        print_r("日运计算添加完成，总共添加计算队列任务数{$taskNum},总共计算用户总数{$totalNum}");
    }

    /**
     * 判断数据表是否存在  不存在则创建
     */
    public function tablesCheck()
    {
        $tables = [
            'zl_fortune_day_20200100',
            'zl_fortune_day_20200200',
            'zl_fortune_day_20200300',
            'zl_fortune_day_20200400',
            'zl_fortune_day_20200500',
            'zl_fortune_day_20200600',
            'zl_fortune_day_20200700',
            'zl_fortune_day_20200800',
            'zl_fortune_day_20200900',
            'zl_fortune_day_20201000',
            'zl_fortune_day_20201100',
            'zl_fortune_day_20201200',
        ];

        foreach ($tables as $tableName)
        {
            $isTable = Db::query('select `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` where `TABLE_SCHEMA`="wechat" and `TABLE_NAME`="' . $tableName . '"');

            if (!$isTable)
            { // 表不存在则创建
                $str = "CREATE TABLE `wechat_backup_07_18_14_43_00`.`{$tableName}` (
                          `id` int(11) NOT NULL AUTO_INCREMENT,
                          `uid` int(11) NOT NULL DEFAULT '0' COMMENT '用户ID',
                          `sun_in_sign` int(2) NOT NULL DEFAULT '0' COMMENT '星座',
                          `date` int(10) NOT NULL DEFAULT '0' COMMENT '日期（20200101）',
                          `star_level` tinyint(1) NOT NULL DEFAULT '0' COMMENT '最高的星级',
                          `rbid` int(11) NOT NULL DEFAULT '0' COMMENT '备份档案ID（zl_fortune_day_recode_backup）',
                          `content` text NOT NULL COMMENT '运势信息',
                          PRIMARY KEY (`id`),
                          KEY `sun_in_sign` (`sun_in_sign`),
                          KEY `star_level` (`star_level`),
                          KEY `rbid` (`rbid`),
                          KEY `uid` (`uid`),
                          KEY `date` (`date`)
                        )  ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户日运信息'";
                // 创建数据库
                Db::execute($str);
            }
        }
        print_r('初始化数据表检查完成' . PHP_EOL);
    }

    public function dataInsert(string $ym, string $dataStr)
    {
        $insetSql = 'INSERT INTO `wechat_backup_07_18_14_43_00`.`zl_fortune_day_' . $ym . '00`(`sun_in_sign`,`uid`,`date`,`star_level`,`rbid`,`content`)  VALUES' . $dataStr;
        $insetSql = rtrim($insetSql, ',');
        Db::query($insetSql);
        print_r($ym . '日运写入完成' . PHP_EOL);
    }

    public function test()
    {
        // Log::write(['12312' => 'dfasdfa', 'sdfasd' => 'dfs', 'ddd' => ['aa' => 'ff']], 'flog_push');

        $jobDataDemo = [
            'type' => 1,
            'title' => '准了',
            'content' => '啥发送到发送到',
            'extras' => [],
            'regids' => [
                '161a3797c86be14869a'
            ],
        ];

        Util::queuePush('push_service', $jobDataDemo);
    }
}
